我在localhost上运行我的servlet程序,我的android代码在同一系统中的模拟器上运行,我想从android客户端向servlet发送一些请求,而servlet程序也应该发回一些数据获取请求后到android,它应该使用响应发送。请让我知道代码。
这是我的android代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.util.Log;
public class CheckHttpClint {
public static void executeHttpPost() throws IOException {
BufferedReader bufferedReader = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
String details = "details";
pairs.add(new BasicNameValuePair("pid", details));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse httpResponse = client.execute(httpPost);
bufferedReader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separater");
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line + NL);
System.out.println(buffer);
Log.i("data send.", null);
}
bufferedReader.close();
String page = buffer.toString();
System.out.println(page);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
}
}
servlet code:
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DBConnection extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
String pid1 = request.getParameter("pid");
out.print(pid1);
out.println("</body></html>");
out.close();
}
}