Http get request not working - java

I got this code, any suggestions why it's not returning any value to the "toBeSplit" String?
I call the method this way.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getData();
}
}).start();
Here is the actual method, i have tried 1000 ways and it just aint working..
private void getData() {
StringBuilder builder = new StringBuilder();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
HttpConnectionParams.setSoTimeout(httpParams, timeout);
HttpClient client = new DefaultHttpClient(httpParams);
String yourUrl = "http://www.ratemyplays.com/form.php";
HttpGet httpGet = new HttpGet(yourUrl);
{
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
toBeSplit = builder.toString();
split2 = toBeSplit.split(",");
}

Use Code:
StringBuilder builder = new StringBuilder();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
HttpConnectionParams.setSoTimeout(httpParams, timeout);
HttpClient client = new DefaultHttpClient(httpParams);
String yourUrl = "http://www.ratemyplays.com/form.php";
HttpGet httpGet = new HttpGet(yourUrl);
{
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
String tempstr = builder.toString();
String str[] = tempstr.split(",");

Try to split as below:
try {
response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
StringBuilder sb = new StringBuilder();
String line = "";
BufferedReader bf = new BufferedReader(
new InputStreamReader(in));
while ((line = bf.readLine()) != null) {
sb.append(line);
}
m_response = sb.toString();
StringBuilder split = new StringBuilder();
split =m_response.split(",");
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Related

About HTTP Server,The client receives the data that is not returned by the server

This is Server and Client code,Please help me to see where the error,It can be post data to the server but httpResponse not received,Tell me why,Thanks!
imagcode: POST
public void dopost(){
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://127.0.0.1:8088");
StringEntity params =new StringEntity("{\"username\":\"De\",\"passwd\":\"REsfg7ufghfgh\",\"public\":\"ERTYU45646\"} ");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.addHeader(new BasicHeader("Cookie","JSESSIONID=B6FF25530B16AB46CA77B08129FECFB3"));
request.setEntity(params);
HttpResponse httpResponse = httpClient.execute(request);
clientread();
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpEntity.getContent(),"UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line + "/n");
}
System.out.println(entityStringBuilder.toString());
JSONObject resultJsonObject = new JSONObject(entityStringBuilder.toString());
System.out.println(resultJsonObject.toString());
}
}
}catch (Exception e) {
throw new RuntimeException(e);
} finally {
httpClient.getConnectionManager().shutdown();
}
}
some server code :SERVER2
Server code is:
else if (key.isWritable()) {
SocketChannel channel = (SocketChannel) key.channel();
JSONObject res1 = new JSONObject();
res1.put("result","OK");
ByteBuffer buffer = ByteBuffer.allocate(1024);
byte[] bytes = res1.toString().getBytes();
buffer.put(bytes);
buffer.flip();
channel.write(buffer);
channel.shutdownInput();
channel.close();
}

SSLException - Hostname in certificate didn't match

I get this exception
javax.net.ssl.SSLException: hostname in certificate didn't match: <domain.com> != <*.hostgator.com> OR <*.hostgator.com> OR <hostgator.com>
when I use this JSON Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, Charset.forName("utf-8")), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
return jObj;
}
}
Does anyone know how to solve this?
On some devices it's working normally like on Galaxy S6 running Android 6.0.1, but on most other devices I get error.
Why some devices have problems with it and others don't?

HttpClient.excute(HttpPost) no response

I constructed an HttpClient, and set timeout parameters.
the code is like this:
while(bufferedinputstream.read()!=-1){
post.setEntity(multipartEntity);
HttpResponse response = httpClient.excute(post);
}
it worked fine for the first several request, and then somehow the response is not returned, and no exception or timeout exception was thrown. Anyone has any idea what's happening?
since you re not getting any errors or exceptions (do you print them out?), you could check the satusCode of your response. Maybe it helps.
(overridden method from my AsyncTask)
protected String doInBackground(String... arg) {
String url = arg[0]; // Added this line
//...
Log.i(DEBUG_TAG, "URL CALL -> " + url);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String mResponse = "";
try {
List<NameValuePair> params = new LinkedList<NameValuePair>();
//...
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse mHTTPResponse = client.execute(post);
StatusLine statusLine = mHTTPResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { //
//get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
mHTTPResponse.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String aux = "";
while ((aux = rd.readLine()) != null) {
builder.append(aux);
}
mResponse = builder.toString();
} else {
//cancel task and show error
Log.e(DEBUG_TAG, "ERROR in Request:" + statusCode);
this.cancel(true);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mResponse;
}

JSONException during AsyncTask

#Override
protected Integer doInBackground(Void... params)
{
String readMyJSON = readMyJSON();
try {
JSONArray jsonArray = new JSONArray(readMyJSON);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
This is not working, during JSONArray jsonArray = new JSONArray(readMyJSON);, JSONException occurs. Could somebody tell me where is the problem? Thanks in advance.
P.S.: Method I use:
public String readMyJSON()
{
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://search.twitter.com/search.json?q=android");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
This method seems to be allright.
In short, the response from twitter is not an JSON array, so you get an exception. If you want the array of results, do the following:
JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = object.getJSONArray("results");
I suggest you read the Twitter API docs. Specifically, https://dev.twitter.com/docs/api/1/get/search.
Can you try this:
JSONArray jsonArray = new JSONArray("["+readMyJSON+"]");
I hope it should work.

How to Get Response From HttpClient in Android 4.0

i have some trouble when i used this code in android 4.0 i did not get Response but i got Response in 2.2,2.3,2.3.3 version
List<NameValuePair> pwadd = new ArrayList<NameValuePair>();
pwadd.add(new BasicNameValuePair("UName", UName));
HttpParams httpParameters = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(
"http://10.0.2.2/new/webser/Load.php");
httppost.setEntity(new UrlEncodedFormEntity(pwadd));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String response = sb.toString();
what should i do in this code to run in android 4.0 version?
try these in an async task. you need to make network stuff in a separate thread anyway
public static String PrepareSendPostData_DetailsActivity(String station_id) {
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url here");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(100);
nameValuePairs.add(new BasicNameValuePair("param_1", "value_1"));
nameValuePairs.add(new BasicNameValuePair("param_2", "ok"));
nameValuePairs.add(new BasicNameValuePair("module", "dbgestion"));
nameValuePairs.add(new BasicNameValuePair("pdv_id", station_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = getResponseBody(response);
if (responseBody != null)
return responseBody;
else
return null;
} catch (ClientProtocolException e) {
Log.e("exception here", e.getMessage().toString());
return null;
} catch (IOException e) {
Log.e("exception here 2", e.getMessage().toString());
return null;
}
}
public static String getResponseBody(HttpResponse response) {
String response_text = null;
HttpEntity entity = null;
try {
entity = response.getEntity();
response_text = _getResponseBody(entity);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e1) {
}
}
}
return response_text;
}
public static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
StringBuilder buffer = new StringBuilder();
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
return buffer.toString();
}
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
hope it helps...

Categories

Resources