HttpURLConnection or HttpPost with settimeout for java 1.4 - settimeout

I'm sorry if this is duplicate or repeated, need suggestion to call url by httppost or HttpURLConnection with setReadTimeout or setConnectTimeout for 15 seconds, the problem is I'm using java 1.4, setReadTimeout() and setConnectTimeout() is not available for java 1.4 package under java.net, any other alternative way, below is my code
URL url;
HttpURLConnection connection = null;
url = new URL(apiURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/json");
connection.setRequestProperty("Content-Length", ""+Integer.
connection.setRequestProperty("Content-Language", "en-US");
my other code
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(apiURL);
StringEntity input = new StringEntity(jsonBvmMEssage);
input.setContentType("text/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
thanks in advance

finally, I found this,
HttpPost postRequest = new HttpPost(apiURL);
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 15000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 15000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(postRequest);
hope this will work, will test and update

Related

How to set up a Windows.Web.Http.HttpClient PostAsync with basic authorization++

How to set up a Windows.Web.Http.HttpClient PostAsync with basic authorization and mediatype in addition to key/value pairs in Json?
I cannot find any good documentation or examples on how to do this.
These official sites offer very little documentation on how to solve this:
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.web.http.httpclient.aspx
Help appreciated! Thanks!
I found an solution that worked for me:
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("client_id", Constants.CLIENT_ID);
pairs.Add("grant_type", "authorization_code");
pairs.Add("code", code);
var formContent = new HttpFormUrlEncodedContent(pairs);
var base64Creds = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Constants.CLIENT_ID, Constants.CLIENT_SECRET)));
var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
httpFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
var client = new HttpClient(httpFilter);
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", base64Creds);
HttpResponseMessage response = await client.PostAsync(new Uri(Constants.GET_TOKEN_URL), formContent);
client.Dispose();
You can try something like this
HttpClient client = new HttpClient();
string jsonContent = JsonConvert.SerializeObject(YourObject);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationTokenString);
StringContent theContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage aResponse = await client.PostAsync(new Uri(UrlValue), theContent);
string responseContent = await aResponse.Content.ReadAsStringAsync();
client.Dispose();
Edit : The above code is using System.Net.Http.HttpClient
But if you would like to use Windows.Web.Http.HttpClient check out this link

setting params and multipart entity in HttpClient

I using HttpClient and httpost to upload my image file along with some parameters.
My code looks like
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("xyz.com");
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name","Temp"));
postParameters.add(new BasicNameValuePair("id","12345"));
httpost.setEntity(new UrlEncodedFormEntity(postParameters));
MultipartEntity entity = new MultipartEntity();
File imgFile = new File("C:\test.img");
FileBody imgFileBody = new FileBody(imgFile);
entity.addPart("multipartcontent", imgFileBody); //No i18n
httpost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpost);
Am not getting the param values in server. Am i doing anything wrong. Please guide me.
httpost.setEntity(new UrlEncodedFormEntity(postParameters));
...
httpost.setEntity(entity);
The multipart entity overrides the URL encoded one completely discarding its content.
You should add param values to the multipart entity as one or several body parts

Upgrading POST request from HttpClient to HttpComponents. What's going wrong here?

I inherited some old code that uses the now-deprecated Apache Commons HttpClient. I was tasked with upgrading it to use the newer Apache HttpComponents. However, I can't seem to get this POST request to function properly. The server keeps complaining that Content-Length = 0. I'm fairly certain that it's a problem with my conversion of how parameters are added.
The old HttpClient code looks something like this:
PostMethod postMethod = null;
int responseCode = 0;
try{
HttpClient httpClient = new HttpClient();
postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
...
postMethod.addParameter(paramName, request);
responseCode = httpClient.executeMethod(postMethod);
...
}
And here are my HttpComponents replacements:
HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
HttpClient httpClient = new DefaultHttpClient();
postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
...
BasicHttpParams params = new BasicHttpParams();
params.setParameter(paramName, request);
postMethod.setParams(params);
httpResponse = httpClient.execute(postMethod);
responseCode = httpResponse.getStatusLine().getStatusCode();
...
}
The servlet my code it talking to is using Apache Commons FileUpload. Here is the code it catches on when it receives my request:
ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
throw new IOException("Could not construct ServletRequestContext object");
It used to pass this test just fine. Now it doesn't. I've tried all kinds of alternatives, such as using the header, or passing request as a URLEncoded query. Have I made a mistake in my upgrade, somewhere?
Note: I can't just change how the servlet receives my request, because then I'll have to change a number of other apps that talk to it, and that's too big a job.
To set the request body, you can use HttpPost's setEntity() method. You can explore the available entity types here. This would replace the BasicHttpParams code.
To send a form entity, for example:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://someurl");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "value"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = client.execute(httpPost);

I want to recover the posts of my Facebook account to simple table, but I am facing some problems

I am using C# and ASP.NET to code this. I don't want the user to be forced to log in and authorize my facebook app, so I wrote this code to get my token that works fine:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=MYID&client_secret=MYSECRET&user_id=MYUSERID&grant_type=client_credentials");
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result1 = sr.ReadToEnd();
sr.Close();
myResponse.Close();
string token = result1.Substring(13, result1.Length - 13);
Then I wrote this code to get my recent posts:
HttpWebRequest myRequest1 = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}","https://graph.facebook.com/app/posts?access_token=",token));
myRequest1.Method = "GET";
WebResponse myResponse1 = myRequest1.GetResponse();
//StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream(), System.Text.Encoding.UTF8);
StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream());
string result2 = sr1.ReadToEnd();
sr1.Close();
myResponse1.Close();
How can I quickly transform this JSON object into a table?

How to call a GwtServiceImpl Servlet from external application?

I have developed a Gwt application and need now to call its remote service implementation
from another java application. Is there a method that given a List of Java Objects can transform them in a format suitable for invoking the get service servlet?something like:
myObject = .......
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:8080/ppp//org.yournamehere.Main/gwtservice");
String serialized = <somelibrary.serialize>(myObject);
StringEntity input = new StringEntity(serialize);
input.setContentType("text/x-gwt-rpc; charset=UTF-8");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
Although, I haven't tried it the following link seems to be what you are looking for
http://googlewebtoolkit.blogspot.com/2010/07/gwtrpccommlayer-extending-gwt-rpc-to-do.html