I am trying to maintain the login info with session in android.
I am sure that all of my codes on the server are OK cause I have tested them with normal web browsers and also the android webview.
I have checked lots of similar questions on stackoverflow but none have worked for me so far.
here is what I have done...
#Override
protected String doInBackground(String... urls) {
try {
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPost = new HttpPost(urls[0]);
httpPost.setEntity(new UrlEncodedFormEntity(params));
//HttpResponse httpResponse = httpClient.execute(httpPost);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = reader.read()) != -1)
sb.append((char) ch);
Content = sb.toString();
} catch (IOException e) {
Log.e("JsonError", e.getMessage());
}
return Content;
}
#Override
protected void onPostExecute(String page_output) {
Dialog.dismiss();
try {
Log.i("data", page_output);
TextView tv = (TextView) context.findViewById(R.id.textView);
tv.setText(Content);
} catch (Exception e) {
e.printStackTrace();
}
}
can you please help me with this?
Related
I am sending Https request to mysql server but not getting the response while performing the same task on localhost it is working. I have no experience using Https, please give me solution and explain difference between Http and Https request sending to mysql server, hope someone help me thanks in advance.
This is my code
protected String doInBackground(String... params) {
String emailSend = params[0];
String tokenSend = params[1];
String deviceIdSend = params[2];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailSend));
nameValuePairs.add(new BasicNameValuePair("token", tokenSend));
nameValuePairs.add(new BasicNameValuePair("deviceId", deviceIdSend));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://xyz/xyz/xyz.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String resultN) {
super.onPostExecute(resultN);
String s = resultN.trim();
//dialog.dismiss();
if (s.equalsIgnoreCase("success")) {
if (result.contains("Pass")) {
I am trying to get the USD average price 30d for bitcoins from here: http://api.bitcoincharts.com/v1/weighted_prices.json. The Json code I have does not work in the try/catch, and the error is a null (I have tried looking into other questions but all of them seem to return errors, whereas mine just returns a null):
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dogewidget);
TextView btctest = (TextView) findViewById(R.id.title);
//Create a new HTTP Client
DefaultHttpClient httpclient = new DefaultHttpClient();
//Setup the get request
HttpPost httppost = new HttpPost("http://api.bitcoincharts.com/v1/weighted_prices.json");
//Depending on web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = reader.readLine();
JSONObject jObject = new JSONObject(result);
JSONObject jsubObject = jObject.getJSONObject("USD");
String btcjson = jsubObject.getString("30d");
btctest.setText(btcjson);
} catch (Exception e) {
e.printStackTrace();
Log.e("error", "" + e.getMessage());
btctest.setText("Error " + e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
}
}
Any help would be appreciated! Thanks.
Try this code.
private void get_value(String php) {
String responseString = null;
try{
HttpClient httpclient = new DefaultHttpClient();
String url ="your_url";
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Toast.makeText(getApplicationContext(),responseString,1000).show();
//The below code is for Separating values.It may varies according with your result
JSONArray ja = new JSONArray(responseString);
int x=Integer.parseInt(ja.getJSONObject(0).getString("your_string_name"));
} catch(Exception e) {
}
}
The following Code is not able to connect to SQLite.
public class MainActivity extends ListActivity {
JSONArray jArray; String result = null; InputStream is = null;
StringBuilder sb=null;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(); //http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
} //paring data
int Ravid_id;
String Ravid_Name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
Ravid_id=json_data.getInt("Ravid_id");
Ravid_Name=json_data.getString("Ravid_Name");
}
} catch(JSONException e1){
Toast.makeText(getBaseContext(), "No found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
This is just a guess and related to an often posted issue: you should not perform any network operations on the main thread. This code ...
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
... should be in placed in an AsncTask or Service. See this post for an example how to fix this issue (usually an android.os.NetworkOnMainThreadException).
I am working on an application that allows the user to upload an image to server. I am getting 500 internal server error .I cant seem to find anything related to this error which would solve my problem. My code is as follows:
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url){
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bitmap.compress(CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.155.103.167:9090/RestServer/rest/todos");
String fileName = String.format("File_%d.jpg", new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
ContentBody mimePart = bab;
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", bab);
postRequest.setEntity(reqEntity);
postRequest.setHeader("Content-Type", "application/json");
int timeoutConnection = 60000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
System.out.println("Response: " + response.getStatusLine());
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
txt.setText("NEW TEXT"+s);
} catch (Exception e) {
// handle exception here
e.printStackTrace();
System.out.println(e.toString());
}
return null;
}
}
All HTTP 5xx codes indicate a problem on the server side specifically; you're not getting a 4xx error like 400 Bad Request or 413 Request Entity Too Large that indicates that your client code is doing something wrong. Something on the server is going wrong (such as a misconfigured upload directory or a failed database connection), and you need to check your server logs to see what error messages are appearing.
Use this code to upload images It's working fine for me
public class UploadToServer extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args){
String status="";
String URL = "";
try{
Log.d("Image Path ======",TakePicture.file.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
File file = new File(TakePicture.file.toString());
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("Content-Disposition", new StringBody("form-data"));
reqEntity.addPart("name", new StringBody("Test"));
reqEntity.addPart("filename", bin);
reqEntity.addPart("Content-Type", new StringBody("image/jpg"));
httppost.setEntity(reqEntity);
Log.d("Executing Request ", httppost.getRequestLine().toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.d("Response content length: ",resEntity.getContentLength()+"");
if(resEntity.getContentLength()>0) {
status= EntityUtils.toString(resEntity);
} else {
status= "No Response from Server";
Log.d("Status----->",status);
}
} else {
status = "No Response from Server";
Log.d("Status----->",status);
}
} catch (Exception e) {
e.printStackTrace();
status = "Unable to connect with server";
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
}
}
I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}