基本的にポート 8080 ですべてのリクエストをリッスンし、それらをコンソールに書き込む、非常に単純な Java サーバーを実装しました。
私のコードは一度、正常に動作します。ただし、サーバーを再起動するたびに、要求は 1 つしかかかりません。
サーバーコード:
public class RunServer {
public static void main(String[] args) {
final int port = 8080;
final String path = "/android";
try {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); //Create the server to listen for incoming requests on the specified port
server.createContext(path, new HttpHandler() { //Set a handler for incoming requests to the specific path
@Override
public void handle(HttpExchange arg0) throws IOException { //This method is called when new requests are incoming
InputStreamReader isr = new InputStreamReader(arg0.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
System.out.print(query);
} });
server.setExecutor(null); //Default executor. Other executors may be used to e.g. use a threadpool for handling concurrent incoming requests.
server.start(); //Start the server.
} catch (Exception e) {
e.printStackTrace();
}
}
}
このクライアントを使用してサーバーに投稿しています:
public class MyAsyncTask extends AsyncTask<String, String, Void>{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.5:8080/android");
String s;
@Override
protected Void doInBackground(String... params) {
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
nameValuePair.add(new BasicNameValuePair("message",
"Hi, trying Android HTTP post!"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
return null;
}
}