我正在创建一个应用程序,我将一些参数发送到我的Web服务,现在它正在本地主机上运行,它给了我json响应。不知何故,在 HttpResponse httpResponse = httpClient.execute(httpPost); 之后,它无法正常工作。任何人都可以帮忙。 PS。我的网络服务工作正常
test_class.java
package com.vitarkasolutions.tracker;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.gson.Gson;
public class test_class extends Activity{
final static String url = "http://10.0.2.2/tracker/index.php" ;
String xyz ="";
String tag ="login";
String name="varun";
String email="varun@gmail.com";
int lat= 10;
int lang = 20;
int phone_no= 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
registerUser(name, email, tag, phone_no, lat, lang);
}
});
}
@SuppressWarnings("unchecked")
public void registerUser(String name, String email,String register_tag, int phone_no ,int lat , int lang )
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("phone_no",String.valueOf(phone_no)));
params.add(new BasicNameValuePair("lat",String.valueOf(lat) ));
params.add(new BasicNameValuePair("lang", String.valueOf(lang)));
try {
parsing data = new parsing();
data.execute(params);
//AsyncTask parsing =new parsing().execute(params);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class parsing extends AsyncTask<List<? extends NameValuePair>, Void, Void> {
// Making HTTP request
@Override
protected Void doInBackground(List<? extends NameValuePair>... params) {
// TODO Auto-generated method stub
Log.e("tag", "parse function called");
try{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Log.d("tag", "post");
httpPost.setEntity(new UrlEncodedFormEntity(params[0]));
Log.d("tag", "entity");
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.d("tag", "response");
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
Log.d("not Connected", "connected");
}else{
Log.d("Connected", "connected");
}
Log.d("Con", "connected");
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
Reader Reader = new InputStreamReader(is);
Log.e("tag2", is.toString());
Gson gson = new Gson();
user user = gson.fromJson(Reader,user.class);
Log.e("tag3", "done");
Log.e("tag4", user.toString());
Log.e("tag4", user.name);
Log.d("tag4", user.email);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
答案 0 :(得分:0)
Use this code as a sample for webservice and download the jersey jar and add it to your lib
使用下载:
https://jersey.java.net/download.html
使用以下程序添加jar文件: -
右键单击项目---&gt;构建路径---&gt;配置构建路径...--->在左侧,您必须选择Java Build Path ---&gt; Libraries --- &gt;添加外部JAR ---&gt; ok ---&gt; ok
希望这能解决问题
package com.example.login;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.login.ConnectionDetector;
public class MainActivity extends Activity
{
public EditText uname,pwd;
ImageView btnlog1;
public Button btncancel1;
public String db_select;
String mUname;
String mPwd;
String temp;
Intent intObj;
Intent intent = null;
Boolean isInternetPresent = false;
ConnectionDetector cd;
private String SERVICE_URL = "http://100.2.1.97:8080/Database/path";
//private String SERVICE_URL = "http://10.1.1.138:8080/Database/path";
private final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MainActivity.this.setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
btnlog1=(ImageView)findViewById(R.id.login);
//btncancel1=(Button)findViewById(R.id.button2);
//SERVICE_URL=ServerURL.URL+"/msd";
btnlog1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
mUname=uname.getText().toString();
mPwd=pwd.getText().toString();
// display("Login clicked");
if(!mUname.equalsIgnoreCase("") &&
!mPwd.equalsIgnoreCase(""))
{
cd = new
ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
//Toast.makeText(MainActivity.this,
isInternetPresent, Toast.LENGTH_LONG).show();
if(isInternetPresent)
{
try
{
validat_user(mUname,mPwd);
}
catch(Exception e)
{
display("Network error.\nPlease check with
your network settings.");
uname.setText("");
pwd.setText("");
}
}
else
{
display("No Internet Connection...");
}
}
else
{
display("Please enter the data in all Required
fields...");
}
}
});
}
public void display(String msg)
{
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
private void validat_user(String stg1, String stg2)
{
db_select=stg1;
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Login
in progress...");
wst.addNameValuePair("EMP_ID", stg1);
wst.addNameValuePair("EMP_PWD", stg2);
wst.execute(new String[] { SERVICE_URL });
}
@SuppressWarnings("deprecation")
public void no_net()
{
display( "No Network Connection");
final AlertDialog alertDialog = new
AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("You don't have internet connection.\nElse please
check the Internet Connection Settings.");
//alertDialog.setIcon(R.drawable.error_info);
alertDialog.setCancelable(false);
alertDialog.setButton("Close", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.cancel();
MainActivity.this.finish();
System.exit(0);
}
});
alertDialog.setButton2("Use Local DataBase", new
DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
display( "Accessing local DataBase.....");
alertDialog.cancel();
}
});
alertDialog.show();
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT =3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
@SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
@Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0].toString();
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
@Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost= new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
}
catch (Exception e) {
// display("Remote DataBase can not be connected.\nPlease check network
connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{
//display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
jso = new JSONObject(response);
String status = jso.getString("status");
// display("Welcome : "+UName);
if( status.equalsIgnoreCase("") || status==null ||
status.equalsIgnoreCase("Failed"))
{
reset();
}
else
{
//display(status);
intObj=new
Intent(MainActivity.this,pdf.class);
startActivity(intObj);
MainActivity.this.finish();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
public void reset()
{
display("Entered User ID / Password is incorrect.\nPlease enter valid User ID &
Password.");
pwd.setText("");
uname.setText("");
}
}