POST HttpRequest using MultipartEntityBuilder and without deprecated classes - java

I use this method on my code and works fine, but since API22 HttPost, HttpClient, HttpEntity... are deprecated.
I know that the correct update of this code is using HttpURLConnection but I don't know how to use it with my parameters on a MultipartEntityBuilder.
public JSONObject makeHttpRequest(String url, MultipartEntityBuilder datos) {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(datos.build());
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStreamToJSON(is);
}
EDIT: So, I changed my code and now the only deprecated class is HttpEntity, I keep searching, this is the updated code:
public JSONObject makeHttpRequest(String url, MultipartEntityBuilder datos) {
try {
HttpEntity entity = datos.build();
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-length", entity.getContentLength() + "");
conn.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
entity.writeTo(os);
os.close();
InputStream is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStreamToJSON(is);
}

Please refer this android HttpUrlConnection send post and params get request

Related

connection time out in godaddy server

if face problem just in Godaddy server when executing google API the request return connection time out,
only this request.
but on my other servers (digital ocean and local server), it runs and everything is well and same code and the same configuration
String dataSTR = data.toString();
HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send");
StringEntity params = new StringEntity(dataSTR, "UTF-8");
String key = "key=" + authKey;
request.addHeader("Authorization", key);
request.addHeader("content-type", "application/json");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("content-type", "charset=UTF-8");
request.setEntity(params);
System.out.println(request);
System.out.println("______");
HttpResponse response;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
System.out.println(response);
} catch (ClientProtocolException e) {
LOGGER.error(e.getMessage(), e);
return false;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return false;
}

How can I set default headers for all requests?

I have a lot of requests. How can I set default headers for all requests? Please, give me examples
Now My code look like this:
HttpPost request = new HttpPost(url);
StringEntity params = null;
try {
params = new StringEntity(o.writeValueAsString(auth));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.addHeader("content-type", "application/json");
request.setEntity(params);
try {
client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
So I have many requests like this
Since you're using the HttpClientBuilder, why not try using its setDefaultHeaders() method?
HttpClientBuilder client = HttpClientBuilder.create();
Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
client.setDefaultHeaders(header);
HttpPost request = new HttpPost(url);
StringEntity params = null;
try {
params = new StringEntity(o.writeValueAsString(auth));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.setEntity(params);
try {
client.build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
Hope that helps!
The most awkward are the try-catches. Best would be to throw them to the caller, and rely on the logging there.
However a single try-catch is possible too. There the style declaration of var + try{ assigning to var } processing var should better be try { declaration + assigning + processing }
Then one already gets shorter, more readable code.
HttpPost request = new HttpPost(url);
request.addHeader("content-type", "application/json");
try {
request.setEntity(new StringEntity(o.writeValueAsString(auth)));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
Logger.log(Level.SEVERE, e);
}
The HttpClient part is still a bit dubious, and could be reduced without declaration.
Alternatives exist like using annotations, Spring and some more declarative techniques. But this is short enough.

HttpConnection don't close

I want to close the get request connection but,it didn't closed.
Its my code block
Edit code block but doesn't work again..
try {
HttpClient client = new DefaultHttpClient();
URI website = website = new URI("http://"+IPAdres+"/?Arduino="+Komut);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
request.abort();
client.getConnectionManager().shutdown();
client.getConnectionManager().closeExpiredConnections();
} catch (URISyntaxException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
I want to close connection after request
Android ways are little different from java ways. Can yo try this approach?
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
To read more on this try this link

How to resolve "HTTP Error 411. The request must be chunked or have a content length." in java

I am using HttpConnect and trying to get some token from the server. But whenever I try to get the response, its always saying you have not set or problem with content length even I tried to set the content length in many different ways
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("X-DocuSign-Authentication", httpAuthHeader);
conn.setRequestProperty("Accept", "application/json");
if (method.equalsIgnoreCase("POST")) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
conn.setDoOutput(true);
}
status = conn.getResponseCode(); // triggers the request
if (status != 200) { //// 200 = OK
errorParse(conn, status);
return;
}
InputStream is = conn.getInputStream();
You're setting a content-length but never sending a request body.
Don't set the content-length. Java does it for you.
NB setDoOutput(true) sets the method to POST.
Moving away from HttpConnect to HttpClient worked for me. So I moved away from HttpURLConnection and created an http HttpClient object and call execute methods to get data from the server.
Below is the code which make http request using HttpClient rather HttpURLConnection
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(authUrl);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("phone", "phone");
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
String response = getResponseBody(inputStream);
System.out.println(response);
} catch (ClientProtocolException e) {
System.out.println("ClientProtocolException : " + e.getLocalizedMessage());
} catch (IOException e) {
System.out.println("IOException:" + e.getLocalizedMessage());
} catch (Exception e) {
System.out.println("Exception:" + e.getLocalizedMessage());
}

Android - How to Download XML Files with Android 4.0?

I will Download XML File with Android 4.0 my old Code works at Android 2.3.3 here:
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
I must have an Example without DefaultHttpClient .
From Gingerbread (2.3) and up, the preferred method for retrieving HTTP data is HttpUrlConnection. You might wanna check this blog post for details. You may also want to check the Javadoc for HttpUrlConnection
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
your problem may be the "strict mode" here.
you have to do http requests with a thread or an AsyncTask.
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
//http request here
//return the response as string
}
#Override
protected void onPostExecute(String result) {
//set the the data you get
}
then:
new RequestTask().execute(yourHttpRequestString)

Categories

Resources