clientprotocolexception DefaultHttpClient.execute() - android

I am using the following code to request a response from a webserver. The server sends a malformed response without headers which causes a ClientProtocolException. I have tried to use inspectors but they are not called before the exception is fired. I cannot change the server (it is within an embedded device, ALFA router R36).
Any suggestions to deal with this problem (btw: the code works perfect if the server response is well-formed)
Thanks in advance, Ton
class httpRequestTask extends AsyncTask <Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
protected Integer doInBackground(Integer... requestCode) {
Integer reqStatus = 0;
String url = "http://192.168.2.1/";
String authString = ("admin:admin");
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: url += "/adm/status_info.asp"; break;
case Constants.HTTP_SCAN: url += "/goform/getUsbStaBSSIDListForm"; break;
}
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
HttpResponse response;
request.setURI( new URI( url));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
response = client.execute(request);
reqStatus = response.getStatusLine().getStatusCode();
String line;
BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
while((line = in.readLine()) != null) respTxt.append(line);
} catch ( ClientProtocolException e){
Log.e("ALFA", "HTTPReq:ClientProtocolException " + e.toString());
} catch ( IOException e){
Log.e("ALFA", "HTTPReq:IOException " + e.toString());
} catch ( Exception e){
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}

Looking further to find a solution to the problem I found a suggestion to use a socket to request the server. I used Fiddler in combination with a browser on my PC to examine the data send to and received from the buggy server and read an article on Wikipedia, explaining the HTTP protocol. With that info and by using a Socket, I wrote a very basic httpRequestHandler than deals with the miss formed response from the buggy web server.
class httpSocketRequest extends AsyncTask<Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
int reqStatus = 0;
protected Integer doInBackground(Integer... requestCode) {
String ip = "192.168.2.1";
String path = "";
String authString = ("admin:admin");
Socket socket = null;
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: path = "adm/status_info.asp"; break;
case Constants.HTTP_SCAN: path = "goform/getUsbStaBSSIDListForm"; break;
}
try {
socket = new Socket( ip, 80);
PrintWriter out = new PrintWriter( socket.getOutputStream());
out.println( "GET http://" + ip + "/" + path + " HTTP/1.0");
out.println( "Authorization: Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
out.println( "");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
int lineCnt = 0;
while((line = in.readLine()) != null){
if( lineCnt >= 0){
lineCnt++;
if(lineCnt == 1){ // first line should start with "HTTP/1.x " followed by a 3 digit status
if( line.length() > 12 && line.substring(0, 6).equals("HTTP/1")){
int p = line.indexOf(" ");
reqStatus = Integer.parseInt(line.substring(p+1, p+4));
continue;
} else { // not a well formed response
lineCnt = -1; // just put everything into respTxt
reqStatus = 200; // and assume everything went OK
}
} else if( lineCnt > 1){ // process rest of headers
if( line.length() == 0){
lineCnt = -1; // done with headers
} else {
// TODO insert code to process other headers
}
continue;
}
}
respTxt.append(line + "\n");
}
} catch (Exception e) {
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
} finally {
try {
if( socket != null) socket.close();
} catch (IOException e) {
Log.e("ALFA", "HTTPReq:Exception closing socket" + e.toString());
}
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}

Related

SocketTimeoutException in HttpURLConnection randomly in getResponseCode

I am getting following error in con.getResponseCode()
java.net.SocketTimeoutException: failed to connect to example.com (port 80) after 3000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:223)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:475)
at java.net.Socket.connect(Socket.java:861)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:152)
at com.android.okhttp.Connection.connect(Connection.java:101)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
First time when it gets called it works perfectly.
But it stops working after it and it may start working randomly after some time.
public class HTTPLoader {
public static String loadContentFromURLGET(String urlString,List<String[]> getVars,Context context){
int retry = 0;
HttpURLConnection con=null;
BufferedReader in = null;
StringBuffer response=null;
if (!isConnectingToInternet(context)){
return "{'error':'No Internet connection!'}";
}
while (retry++<=RETRY_CNT) {
try {
String urlParameters = "";
for (String[] var : getVars) {
urlParameters += var[0] + "=" + URLEncoder.encode(var[1], "UTF-8") + "&";
}
if (urlParameters.length() > 1) {
urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
}
if (urlString.charAt(urlString.length() - 1) != '?') {
urlString += "&";
}
URL url = new URL(urlString + urlParameters);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(3000);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoInput(true);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
retry = RETRY_CNT+1;
break;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}finally {
if (in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (con!=null) {
con.disconnect();
}
in = null;
con = null;
}
}
if (response!=null)
return new String(response);
return "{'error':'No Internet connection!'}";
}
}
This loadContentFromURLGET is getting called from IntentService
public class ChatUtil extends IntentService{
protected String loadAllChats(String date){
String response = "";
try {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = sharedPreferences.getString(QuickstartPreferences.EMAIL, "");
List<String[]> postVars = new ArrayList<>();
postVars.add(new String[]{"getconversation", "yes"});
postVars.add(new String[]{"user_id", email});
postVars.add(new String[]{"last_date", date});
String urlString = getString(R.string.get_conversation_url);
response = HTTPLoader.loadContentFromURLGET(urlString, postVars,getApplicationContext());
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("error")) {
//Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
return jsonObject.getString("error");
}
}catch (JSONException e) {
}
}
protected void onHandleIntent(Intent intent) {
String task = intent.getStringExtra(QuickstartPreferences.CURRENT_TASK);
Intent nintent;
String date = "";
String[] arr3 = new NewsDBUtil(getApplicationContext()).getLastChatEntry(null);
if (arr3!=null)
date = arr3[1];
loadAllChats(date);
nintent = new Intent(QuickstartPreferences.LOADING_ALL_CHAT);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(nintent);
}
}
Tried closing and disconnecting stream in finally block.
But no Success.
you can put con.getResponseCode(); between try ...catch block if it throw SocketTimeoutException Exception make another try , but make sure you extend your timeout
if (responseCode != 200) {
....
...
} catch (final java.net.SocketTimeoutException e) {
// connection timed out...let's try again
}
may this help
Without specific ContentLength via setFixedLengthStreamingMode
I found some devices generated incomplete http request
cause the server has to wait until either server or client timed out
you can use wireshark to analyze the problem

Passing special characters over socket connection

I have built a chat application in Android powered by sockets. The messages send and receive fine, so long as the user does not send messages with special characters, ie. Hey, it's me, will not work, but Hey its me, will, the comma and apostrophe prevent the message from being delivered.
I attempted using URLEncoder, but that did not allow the unique characters to be sent.
Sending message method:
public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8")
+ "&message=" + URLEncoder.encode(message, "UTF-8")
+ "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
+ "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
+ "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
+ "&gcmregid=" + gcmRegistrationID
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
with
SocketerInterface socketOperator = new Socketer(this);
and Socketer class as:
public class Socketer implements SocketerInterface {
// Have to set the proper ports that apache is runnign on as well as your
// computers IP address: ie. ip:4430 or 800
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
// + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/"; // Google Compute Engine Access
//+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access
+ ipAddress.getFeastChatServer(); // For Heroku access
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new
// PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.v("XML MESSAGE", inputLine);
if (inputLine.equals("exit") == false) {// as long as have
// noted exited yet,
// will continuing
// reading in
Log.v("XML MESSAGE", inputLine);
// appManager.messageReceived(inputLine);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket
.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ", "");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params) {
URL url;
String result = new String();
try {
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
// Testing to remove <head/> tag from Google App Engine
//return result.replace("<head/>","");
return result;
}
public int startListening(int portNo) {
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
// e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
// e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket",
"Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening() {
this.listening = false;
}
public void exit() {
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
.hasNext();) {
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}
How can I format/encode to allow sending these messages?
Java uses UTF-16 for internal String representation, but it looks like you are using UTF-8, but you aren't doing anything special to convert it from UTF-8 when reading it from BufferedReader. In the params, try specifying UTF-16 instead.
From the Java String documentation:
A String represents a string in the UTF-16 format

Unable to set notifyDataSetChanged in Android

I have a case where I load a set of 10 images via WebService and and on further scrolling, I call upon the second WebService which load the next 10 images. I am able to load all the images from WebService but I am doing something silly that removes the first 10 images and re-assigns it with the next 10 images while calling the 2nd web service. I have tried notifyDataSetChanged() but it has no effect. The code is as follows :
CODE :
MainActivty :
new WebServicesClass().generateSampleData(); -->1st WebService
mGridView.setOnScrollListener(this);
mGridView.setOnItemClickListener(this);
#Override
public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) {
Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem +
" visibleItemCount:" + visibleItemCount +
" totalItemCount:" + totalItemCount);
// our handling
if (!mHasRequestedMore) {
System.out.println("Inside the requested more");
int lastInScreen = firstVisibleItem + visibleItemCount;
if (lastInScreen >= totalItemCount) {
Log.d(TAG, "onScroll lastInScreen - so load more");
mHasRequestedMore = true;
new WebServicesClass().onLoadMoreItems(); --> 2nd WebServiceCall
mHasRequestedMore = false;
}
}
}
WebServicesClass :
1st WebService :
onDoInBackGround :
#Override
protected String doInBackground(Void... urls) {
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(
"http://demo.bsetec.com/fancyclone/android/users/products?user_id=2&limit=0");
HttpResponse response = httpclient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
System.out.println("Buffered Reader " + reader.toString());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag",
"Error converting sms response result " + e.toString());
}
System.out.println("Result: " + result);
try {
limit_for = 0;
OpenHttpConnection(image_url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
OpenHttpConnection :
public InputStream OpenHttpConnection(String image_url)
throws IOException {
int response = -1;
JSONObject jsonresponse;
String first_image = null;
try {
jsonresponse = new JSONObject(result);
Log.i("Inside OpenHttp", result);
if (result != null) {
try {
JSONObject status = jsonresponse
.getJSONObject("status");
// looping through All Contacts
if (status != null) {
products = status.getJSONArray("products");
dreamt_product_list = status
.getJSONArray("dreamit_products");
System.out.println("Dreamt Products list are "
+ dreamt_product_list.getJSONObject(0)
.names());
System.out.println("The value of string limit is "
+ limit);
System.out.println("The limit_for value is "
+ limit_for);
for (int p = limit_for; p < load_limit; p++) {
System.out.println("Products names: "
+ products.getJSONObject(p).names());
System.out.println("Item Name "
+ products.getJSONObject(p).getString(
"name"));
product_name = products.getJSONObject(p)
.getString("name").toString();
cost = products.getJSONObject(p).getString("saleprice").toString();
product_id = products.getJSONObject(p)
.getString("id");
username = products.getJSONObject(p).getString("username").toString();
System.out.println("Getstring: "
+ products.getJSONObject(p).getString(
"images"));
String images_list = products.getJSONObject(p)
.getString("images");
images_list = images_list.replaceAll("\"", "");
String regex = images_list.replaceAll(
"\\[|\\]", "");
System.out
.println("The images without bracket are "
+ regex);
for (String comma_token : regex.split(",")) {
for (int i = 0; i < 1; i++) {
System.out
.println("First Image name is "
+ comma_token);
first_image = comma_token;
System.out
.println("Image in first image is "
+ first_image);
}
break;
}
System.out.println("I am here");
image_url = "http://demo.bsetec.com/fancyclone/uploads/approved_items/"
+ first_image;
URL url = new URL(image_url);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException(
"Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
compressed_image = image;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inJustDecodeBounds = true;
options.inSampleSize = 1;
options.inJustDecodeBounds = false;
image = BitmapFactory.decodeStream(in,
null, options);
// in.reset();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
item = new RowItem(image, product_name, cost,
product_id, dream_status,username);
rowItems.add(item);
}
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%" + rowItems.size());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out
.println("Caught Exception in the 2nd try block");
e.printStackTrace();
}
}
} catch (Exception e) {
System.out.println("Caught exception");
}
System.out.println("Ending OpenHttpConnection");
return in;
}
onPostExecuteMethod :
mAdapter = newDynamicHeightAdapter(MainActivity.getContext(),R.layout.repeat_items,rowItems);
System.out.println("ADapter size: "+mAdapter.getCount());
MainActivity.mGridView.setAdapter(mAdapter);
2nd WebService :
onDoInBackGround :
The code is SAME as the first doInBackGround().OpenHttpConnection is also the same.
onPostExecuteMethod :
mAdapter.notifyDataSetChanged(); -->Not working
When I call the WebService initially, it retrieves the first 10 images as it is supposed to do. But when the 2nd WebService is called at onScroll, then it REPLACES the initial 10 images with the 10 images obtained FROM 2nd WEBSERVICE. All I want to know is, how do I UPDATE it WITHOUT REPLACING ? Any help will be much appreciated guys. I am happy to help you with any queries.
UPDATE :
rowItems.addAll(rowItems);
Is the above code valid ?
NOTE : I am using a external library named StaggeredGridView.
First get the adapter.
YourAdapter adapter=(YourAdapter) mGridView.getAdapter();
adapter.addAll(rowItems);
adapter.notifyDataSetChanged();
Hope this works fine
You pass a collection of objects to the adapter, in your case it is rowItems.
OnScroll you hit a Web service and receives and parse the contents. These new content should be put in separate new arraylist. Say it is newRowContents.
Now, you need to add newRowContent to original row content.
rowItems.addAll(newRowContent);
Your backing datasource is updated now, and your listview needs to be refresh now.
mAdapter.notifyDataSetChanged();

Why does Android not send my second SSL request?

My Android app is talking to a webserver using SSL and GET requests. After switching to API 10 (Gingerbread) the SSL connection works - but only for the first time after the app starts...
The first request is sent by the main activity - after getting a response, another activity starts and sends multiple requests. And none of them is answered. In both cases the request is sent using a litte WebService class that is initiated in a new AsyncTask. After downsizing this alass, the only thing it actually contains is the URL(-String). Each activity starts its own instance of this class.
Here is the method that should do the GET request. As easily visible I included some code to avoid keep-alive - not that I don't like it, but it has been suggested in other answers to do so to avoid problems with multiple connections. Well, it did not work in my case.
public String webGet(String methodName, Map<String, String> params) {
String getUrl = webServiceUrl + methodName;
index++;
final int connectionID = index;
int i = 0;
for (Map.Entry<String, String> param : params.entrySet()) {
if (i == 0) {
getUrl += "?";
} else {
getUrl += "&";
}
try {
getUrl += param.getKey() + "=" + URLEncoder.encode(param.getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
String response;
Log.e("WebGetURL", "["+connectionID+"] " + getUrl);
URL url;
try {
url = new URL(getUrl);
} catch (MalformedURLException e) {
Log.e("WebService", "Malformed URL: " + getUrl);
return null;
}
HttpURLConnection urlConnection;
try {
Log.e("WebGetResponse", "["+connectionID+"] openConnection()");
System.setProperty("http.keepAlive", "false");
if (webServiceSsl) {
Log.e("WebService", "Using HTTPS");
urlConnection = (HttpsURLConnection) url.openConnection();
} else {
urlConnection = (HttpURLConnection) url.openConnection();
}
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Connection","Keep-Alive");
urlConnection.setDoOutput(false);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
} catch (IOException e) {
Log.e("WebService", "I/O exception opening connection: " + e.getMessage());
e.printStackTrace();
return null;
}
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Connection", "close");
try {
urlConnection.connect();
Log.e("WebGetResponse", "["+connectionID+"] getInputStream()");
// This is the last thing I hear from my thread
BufferedInputStream bin = new BufferedInputStream(urlConnection.getInputStream());
Log.e("WebGetResponse", "["+connectionID+"] gotInputStream()");
byte[] contents = new byte[1024];
int bytesRead=0;
StringBuilder strFileContents = new StringBuilder();
Log.e("WebGetResponse", "["+connectionID+"] Waiting for data");
while((bytesRead = bin.read(contents)) != -1) {
String add = new String(contents, 0, bytesRead);
strFileContents.append(add);
}
bin.close();
response = strFileContents.toString();
} catch (IOException e) {
Log.e("WebService", "I/O exception reading stream: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
urlConnection.disconnect();
}
Log.e("WebGetResponse", "["+connectionID+"] " + response);
return response;
}
I have been trying ans searching - I don't get the problem. Actually I cannot test the class on a non-https server currently, so I am unaware if the problem occurs in HTTP as well. However, the handshake seems to work, because the first request works well.
And here is the code that should start the request (final param is the GET content to send):
class ServerDataThread extends AsyncTask<Integer, Integer, String[]> {
#Override
protected String[] doInBackground(Integer... attempts) {
sendActive++;
int count = attempts.length;
String[] responses = new String[count];
for (int i = 0; i < count; i++) {
responses[i] = server.webGet("collector.php", params);
}
return responses;
}
protected void onPostExecute(String[] responses) {
sendActive--;
for (int i = 0; i < responses.length; i++) {
if (responses[i] == null) {
continue;
}
onResponseData(responses[i]);
}
}
}
new ServerDataThread().execute(0);
Could anyone please help me out with a hint what I am doing wrong? Thank you very much!
BurninLeo

HTTP GET on Android

I have a method to insert data into server like this:
public void doInsert(){
try {
// setiap parameter yang akan dikirim melalui http
// harus encode agar
// dapat terbaca dengan baik oleh server
String no_imei = URLEncoder.encode(noImei.getText().toString(), "utf-8");
String nik = URLEncoder.encode(user.getText().toString(), "utf-8");
String pass = URLEncoder.encode(password.getText().toString(), "utf-8");
url += "?no_imei=" + no_imei + "&&nik=" + nik + "&&password=" + pass;
getRequest(url);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Another method that I have:
public void getRequest(String Url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
Toast.makeText(this, "Tambah Data " + request(response) + " ",Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
//Toast.makeText(this, "Tambah Data Gagal !", Toast.LENGTH_SHORT).show();
}
}
And like this:
public static String request(HttpResponse response) {
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
onClick method:
private View.OnClickListener onSave=new View.OnClickListener()
{
public void onClick(View v)
{
//Dbhelper helper = new Dbhelper(UserForm.this);
Cursor c = helper.Login(almagId);
if (noImei.getText().toString().equals("")||
user.getText().toString().equals("")||
password.getText().toString().equals("")
) {
Toast.makeText(UserForm.this, "Data Harus di isi", Toast.LENGTH_LONG).show();
}else if(c.moveToFirst()){
if(noImei.getText().equals(c.getString(0))||
user.getText().equals(c.getString(1))){
Toast.makeText(UserForm.this, "Data Sudah ada", Toast.LENGTH_LONG).show();
helper.close();
}
}else
{
doInsert();
helper.insertUser(noImei.getText().toString(),user.getText().toString(),password.getText().toString());
//Toast.makeText(UserForm.this, "Data Berhasil disimpan", Toast.LENGTH_LONG).show();
}
startActivity(new Intent(UserForm.this,MenuUtama.class));
user.setText("");
password.setText("");
return;
}
};
In the onClick method when response from server SUCCESS I want to do some activity. How can I do that? I tried with condition if my activity not running.
You should probably go with
if (response != null && response.getStatusLine().getStatusCode() == 200) { }
You have to add your activity in AndroidManifest.xml. Refer this link : Using Intent in an Android application to show another activity
looks like login in your if statement is little off.
if(request(response).equals("SUCCESS")){ startActivityForResult(new Intent(this,MainMenu.class))}
first, this does not make sense
if(request(response).equals("SUCCESS"))
what are you trying to do, cast request into response???
second:
.equals("SUCCESS"))
response is not an String object, are you looking for status code??
read over Android's HttpResponse
http://developer.android.com/reference/org/apache/http/HttpResponse.html
Example Code
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//Do Something
}

Categories

Resources