How to get response in put method with Authentication using four Headers.In ios it works fine but not in Android.
Authentication code is generated from the data HMAC-SHA256 with the secret key provided after validation as the key
HttpPut put = new HttpPut(xAuthurl);//url
Log.v("put", "" + put);
try {
put.setEntity(new StringEntity(data, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
Log.e(TAG, "UnsupportedEncoding: ", e1);
}
//Here are the four headers......
put.addHeader("Content-type", "application/json");
put.addHeader("x-Auth-user", Validation.id);//id of the profile
put.addHeader("X-Auth-Hash", hexBytes);// Hexadecimal value
put.addHeader("X-Auth-Time", sdf.format(datetime));//date format in utc
HttpResponse response = null;
try {
response = http.execute(put);
Log.v("response", "" + response.getAllHeaders());
} catch (ClientProtocolException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO
// Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "This is what we get back:"
+ response.getStatusLine().toString() + ", "
+ response.getEntity().toString());
try {
inputStream = response.getEntity().getContent();
} catch (IllegalStateException e1) { // TODO Auto-generated catch
// block
e1.printStackTrace();
} catch (IOException e1) { // TODO Auto-generated catch block
e1.printStackTrace();
}
if (inputStream != null) {
try {
result = convertInputStreamToString(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("result", "" + result);
} else {
result = "Did not work!";
}
return 1;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
result i get is {"Message":"An error has occurred."}
Related
I have set connection timeout and Read timeout but still they are getting ignored, the request just stays on forever. How do I set a timeout such that the request gets cancelled if the timeout is reached ?
This is my code snippet, appreciate your help.
urlConnection = (HttpURLConnection) saveURL.openConnection();
// is output buffer writer
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "text/html");
urlConnection.setRequestProperty("userid", id);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(jsonString);
writer.flush();
// json data
writer.close();
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
int responseCode = urlConnection.getResponseCode();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketTimeoutException soce) {
// TODO Auto-generated catch block
soce.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != urlConnection)
urlConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am not sure if this is the best option, what I did was to set a Timer which I used to do a disconnection on HttpURLConnection once time was up. It seems to work fine so far. If anyone can point out the disadvantages of this approach and suggest a better way, I would appreciate it.
I am trying to read data continuously using the following code:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
readInpt = inputStream.toString();
byteArrayOutputStream.write(buffer, 0, bytesRead);
response = byteArrayOutputStream.toString("UTF-8");
}
textResponse.setText(readInpt);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
But for some reason, it doesn't show me any output in the textbox. any help would be appreciated.
There are at least two issues in your code.
Frist, I'm not sure the method toString() on the inputStream is going to work, because the documentation says it returns a description of the object (which would be different than the string recieved). You might be confusing this with the contents of buffer which might be what you really want.
readInpt = inputStream.toString(); // Probably wrong
Second. You're updating the User Interface from a background thread, inside doInBackground() , which is always forbidden.
textResponse.setText(readInpt); // Forbidden, move somewhere else, e.g. onPostExecute()
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
response = stdIn.readLine();
publishProgress(response);
Log.i("response", response);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
catch (Exception e) {
e.printStackTrace();
}
You cannot print it on text field because the socket will listen to the server socket.If server socket does not send any response it will listen to the socket continuously until the response is received.
I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}
I'm trying to read from a text file under /data/data/package_name/files.
This is my code:
private String readTxt(String fileName)
{
String result = "", line;
try
{
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
while((line = br.readLine()) != null)
{
result += line + "\n";
}
}
catch(Exception e)
{
e.printStackTrace();
}
return result;
}
What am I doing wrong?
You should use the openFileInput Method from your application context. http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
Which will give you a InputStream to your file
Example:
final InputStream is = getApplicationContext().openFileInput(MY_FILENAME_WITHOUT_PATH);
private String getStringFromFile(Context accessClass,String fileName){
String result=null;
FileInputStream fIn;
ContextWrapper accessClassInstance=new ContextWrapper(accessClass);
try {
fIn = accessClassInstance.openFileInput(fileName);
InputSource inputSource=new InputSource(fIn);
InputStream in = inputSource.getInputStream();
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
result = "";
while (( line = buffreader.readLine()) != null) {
result += line;
}
in.close();
Toast.makeText(getApplicationContext(),"File Contents ==> " + result,Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
Getting this error:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
Caused by: java.lang.NullPointerException
at com.Wahoo.BrowseListActivity$DownloadSite.doInBackground(BrowseListActivity.java:79)
at com.Wahoo.BrowseListActivity$DownloadSite.doInBackground(BrowseListActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
... 4 more
Here's my AsyncTask...it crashes only for some users at particular times...not sure why. Perhaps they lose their internet connection mid-query? What am I doing wrong here? Here's my code:
private class DownloadSite extends AsyncTask<String, Integer, String> {
private HttpResponse response;
private InputStream in;
private Context context;
private String html;
private ProgressDialog progress;
#Override
protected String doInBackground(String... params) {
in = null;
String url = "aURLGOESHERE_BUTI'MCENSORING" + params[0] + "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
html = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
} catch (Exception e) {
this.publishProgress();
this.cancel(true);
e.printStackTrace();
}
StringBuilder str = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
html = params[0] + str.toString();
return html;
}
#Override
protected void onPreExecute() {
progress = new ProgressDialog(BrowseListActivity.this);
progress.setIndeterminate(true);
progress.setMessage("Loading...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
CharSequence text = "Connection interrupted...please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), text,
duration);
toast.show();
}
#Override
protected void onPostExecute(String html) {
progress.dismiss();
Context context = BrowseListActivity.this;
Intent stopViewer = new Intent(context, StopActivity.class);
stopViewer.setData(Uri.parse(html + ""));
context.startActivity(stopViewer);
}
}
One thing that you are doing wrong is continuing to execute doInBackground after an error that makes it impossible to continue meaningfully. For instance:
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
If this throws an exception, response is going to be null and there's no point in proceeding further. You'll generate a NullPointerException in the next block of code. That won't be fatal, because you are catching all exceptions there. Further on, though, this pattern repeats and you aren't catching all exceptions.
You should exit prematurely, returning null as the String result. Then you can test for a null in onPostExecute and let the user know what happened in a graceful way.