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
Related
I have the following code using try with resources with CloseableHttpResponse
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
//code...
response = httpClient.execute(target, post);
String responseText = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("Failed sending request", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("Failed releasing response", e);
}
}
}
Can I safely replace with nested try with resources:
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
URIBuilder uriBuilder = new URIBuilder(url);
HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
HttpPost post = new HttpPost(uriBuilder.build());
try (CloseableHttpResponse response = httpClient.execute(target, post)) {
String responseText = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("Failed sending request", e);
}
Or is it better to use a single try with resources block:
try (CloseableHttpClient httpClient = HttpClients.custom().build();
CloseableHttpResponse response = getResponse(httpClient, url)) {
Sometime refactoring to single block is problematic, so I wanted to know the a nested/additional block is a valid solution.
HttpClient never returns a null HttpResponse object. The first construct is simply not useful. Both the second and the third constructs are perfectly valid
Im trying to Update JSON data to Thingspeak channel, but i get 401 error Authorization error. Have sent "writekey" as parameter. Error is
{"status":"401","error":{"error_code":"error_auth_required","message":"Authorization Required","details":"Please provide proper authentication details."}}
` try {
List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
NameValuePair nv5 = new BasicNameValuePair("writeApi_Key",writeApi_Key);
nvPairList.add(nv5);
HttpClient client = HttpClientBuilder.create().build();
HttpPut put= new HttpPut(urlname);
URI uri = null;
try {
uri = new URIBuilder(put.getURI()).addParameters(nvPairList).build();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
put.setURI(uri);
put.setHeader("writeApi_Key", writeApi_Key);
put.setHeader(HTTP.CONTENT_TYPE, "application/json");
put.setHeader("charset", "utf-8");
put.setHeader("Connnection", "keep-alive");
put.setHeader("Cache-Control", "no-cache");
System.out.println("Url header of post:::"+put.toString());
StringEntity entity = new StringEntity(entryobj.toString());
put.setEntity(entity);
System.out.println("Url header of post:::"+put.toString());
HttpResponse response = client.execute(put);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
System.out.println("connection refused");
} else if (response.getStatusLine().equals("0")) {
System.out.println("Update Failed");
}
HttpEntity responseentity = response.getEntity();
String responseString = EntityUtils.toString(responseentity, "UTF-8");
System.out.println(responseString);
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} `
output url is when writeApi_Key and api_key respectively checked outputs are below
Url header of post:::PUT https://api.thingspeak.com/channels/230391.json?writeApi_Key=UEDXXXXXXXXXXXXX HTTP/1.1
Url header of post:::PUT https://api.thingspeak.com/channels/230391.json?api_key+=VG2XXXXXXXXXXXXX HTTP/1.1
Kindly looking for some one who can shed throw light.. Thanks you so much..
Check to make sure that your API key is correct. Many people who have this problem are using zeros ('0') instead of the letter 'O', and vice-versa. '1' and 'l' can be a problem as well.
I have the following code in my program, used for inserting record -
private Void downloadUrl() throws IOException {
String postParameters;
HttpURLConnection urlConnection = null;
postParameters = "name="+ URLEncoder.encode(user.name,"UTF-8")
+"&age="+URLEncoder.encode(user.age+"","UTF-8")
+"&username="+URLEncoder.encode(user.username,"UTF-8")
+"&password="+URLEncoder.encode(user.password,"UTF-8");
if (postParameters != null) {
Log.i("Post", "POST parameters: " + postParameters);
try {
URL urlToRequest = new URL(SERVER_ADDRESS);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(30000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setFixedLengthStreamingMode(
postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters.getBytes());
out.close();
// handle issues
int statusCode = urlConnection.getResponseCode();
Log.e("Response", "The response is: " + statusCode);
} catch (MalformedURLException e) {
// handle invalid URL
Log.e("Response", "invalid URL");
} catch (SocketTimeoutException e) {
// hadle timeout
Log.e("Response", "handle timeout");
} catch (IOException e) {
// handle I/0
Log.e("Response", "handle IO problem");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
return null;
}
The code is showing no errors and the logged entries are
09-27 12:24:17.944 5006-5039/? E/Response﹕ The response is: 200
09-27 12:24:33.729 5006-5118/? I/Post﹕ POST parameters: name=vibha&age=25&username=vib&password=1234
But when I check the database, the new record is not created.
But if I use PHP code in a file and post the same parameters,the records are getting inserted.
My requirement for help and guidance is how to pass the post parameter in the HttpURLConnection class
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
I am trying to parse a response from an InputStream from a HttpURLConnection using the following code.I get an error when trying to get the InputStream.I am just looking to get a response to check if the web-servcice call worked OK.
static final String SOAP_ACTION="http://888topup.com/ImageProcess.svc/UploadImage";
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
obj.put("Vaue", value);
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
OutputStream os=urlConnection.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(os);
byte[] data=obj.toString().getBytes();
bos.write(data);
InputStream is=urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String response;
response=br.readLine();
Log.d(TAG, "Response: "+response);
bos.close();
br.close();
is.close();
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
Here is the Logcat entry for what happened when I tried to run this code:
MainActivity(9628): Error peforming read-write operations
MainActivity(9628): java.io.FileNotFoundException: http://888topup.com/ImageProcess.svc/UploadImage
MainActivity(9628): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.sendStringToServiceUsingRest(MainActivity.java:184)
MainActivity(8989): at com.example.imageuploadtest.MainActivity.access$0(MainActivity.java:149)
MainActivity(8989): at com.example.imageuploadtest.MainActivity$1$1.run(MainActivity.java:66)
EDIT:
The operation as specified in WSDL:
<wsdl:operation name="UploadImage">
<wsdl:input wsaw:Action="http://tempuri.org/IImageProcess/UploadImage" message="tns:IImageProcess_UploadImage_InputMessage"/>
<wsdl:output wsaw:Action="http://tempuri.org/IImageProcess/UploadImageResponse" message="tns:IImageProcess_UploadImage_OutputMessage"/>
</wsdl:operation>
Adding urlConnection.connect() before writing data to the OutputStream does not work either.
EDIT:Using the URL(SOAP_ACTION) and passing jsondata works from Sencha-Touch for someone else who tested it.
Tried passing JSONObject as String instead of byte data.Did not work either?
There were a few mistakes with what I was doing,firstly I was passing the wrong parameter Vaue instead of Value to the service.
JSONObject obj=new JSONObject();
try {
String value_key="Value";
obj.put(value_key, value);
Log.d(TAG,obj.toString());
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
Secondly,I was trying to parse a response when no response was being sent.So, I replace the code to get the InputStream with the following code:
int response=urlConnection.getResponseCode();
The entire code is here:
java.net.URL url=null;
try {
url = new java.net.URL(SOAP_ACTION);
} catch (MalformedURLException e) {
Log.e(TAG, "Bad URL",e);
}
JSONObject obj=new JSONObject();
try {
String value_key="Value";
obj.put(value_key, value);
Log.d(TAG,obj.toString());
} catch (JSONException e) {
Log.e(TAG, "Create JSONObjerct throws an error");
}
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
Log.e(TAG,"Error opening connection",e1);
}
urlConnection.setDoOutput(true);
try {
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "*/*");
//urlConnection.addRequestProperty("Accept-Encoding", "gzip deflate sdch");
urlConnection.setRequestProperty("Content-Type","application/json");
} catch (ProtocolException e) {
Log.e(TAG,"Error setting header",e);
}
try {
urlConnection.connect();
DataOutputStream dos=new DataOutputStream(urlConnection.getOutputStream());
dos.write(obj.toString().getBytes());
int response=urlConnection.getResponseCode();
Log.d(TAG, "Response code: "+response);
urlConnection.disconnect();
} catch (IOException e) {
Log.e(TAG,"Error peforming read-write operations",e);
}
And finally I used this to send the data to the web-service as binary data:
DataOutputStream dos=new DataOutputStream(urlConnection.getOutputStream());
dos.write(obj.toString().getBytes());