Reputation: 563
i am developing an android app, which needs to send a string to web server(written in java).when server receives this string it will automatically fire response.after going through many examples i tried to do this . i used following code to send request.
try{
String url = "https://mywebserver";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "014500000000000000000000** 0000 0030000100700006800006000000000000000 0 I 00000000 00000000000000000000000000000000000073054721143";
// Send post request
con.setDoOutput(true);
//something is wrong after this line
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}catch(Exception e){
tv_str.setText("caught exception");
}
this is not working (generating an exception). and i also tried this example- answer 2 but not working and also, is there any webserver for Testing http post requests. i.e how do i test my request
if there is any other way to do this please tell me as i am new to this
my logcat:
07-08 11:59:37.423: D/dalvikvm(31971): Late-enabling CheckJNI
07-08 11:59:37.713: I/Adreno-EGL(31971): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
07-08 11:59:37.713: I/Adreno-EGL(31971): OpenGL ES Shader Compiler Version: 17.01.10.SPL
07-08 11:59:37.713: I/Adreno-EGL(31971): Build Date: 12/04/13 Wed
07-08 11:59:37.713: I/Adreno-EGL(31971): Local Branch: workspace
07-08 11:59:37.713: I/Adreno-EGL(31971): Remote Branch:
07-08 11:59:37.713: I/Adreno-EGL(31971): Local Patches:
07-08 11:59:37.713: I/Adreno-EGL(31971): Reconstruct Branch:
07-08 11:59:37.764: D/OpenGLRenderer(31971): Enabling debug mode 0
07-08 11:59:37.849: E/Adreno-ES20(31971): <gl_external_unsized_fmt_to_sized:2379>: QCOM> format, datatype mismatch
07-08 11:59:37.849: E/Adreno-ES20(31971): <get_texture_formats:3009>: QCOM> Invalid format!
thanks in advance
Upvotes: 1
Views: 1280
Reputation: 563
yes json is easy. i implemented this and its working fine.. thanks to JLONG and user1369434.
package m.example.postrwq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
Button btnPost;
TextView tvIsConnected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPost = (Button) findViewById(R.id.button1);
tvIsConnected = (TextView) findViewById(R.id.textView1);
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
btnPost.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "my string";
// 6. set json to StringEntity
StringEntity se = new StringEntity(json);
// 7. set httpPost Entity
httpPost.setEntity(se);
// 8. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 9. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 10. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 11. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 12. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected() {
// TODO Auto-generated method stub
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
hope this will help others
Upvotes: 1
Reputation: 805
I use a JSON parser java class, because it is much easier to transport data from the app and server just like user1369434 said. I forgot where I got the code but here it is, create a java class named JSONparser then post this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is 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, "iso-8859-1"), 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) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Then on your Activty do this:
public class YOUR ACTIVITY extends Activity {
JSONParser jParser = new JSONParser();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a Asynctask for the http request
new NAMEOFYOURASYNCTASK().execute();
}
}
and on your asynctask:
class YOURASYNCTASK extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username_GET", dealer_user_name ));
// getting JSON string from URL
json = jParser.makeHttpRequest(YOUR URL HERE, "POST", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
modify your php code to throw JSON files back to the app and. like this:
// array for JSON response
$response = array();
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
you get the idea. this is just a suggestion btw.
Upvotes: 0
Reputation: 2809
Do you really need to use HTTPS
? If yes I guess you should set SSLSocketFactory
for your connection after opening it. Check this answer for more info: https://stackoverflow.com/a/16507195/1407451
I also would like to recomend you not use HttpsURLConnection
itself but take look at some libraries for network comunications like Retrofit or Volley. For me it seems to be much easer to use.
Upvotes: 0
Reputation: 489
Just a hint for you: I think it would be easier to use JSON in combination with GSON (instead of a simple String) to transport your data between the app and the webserver.
Upvotes: 0