Open zhdh2008 opened 6 years ago
日志 `package com.johnson4droid.client.log;
/**
{@code
{@code
{@code
{@code
{@code
{@code
`package com.johnson4droid.client.log;
import java.io.EOFException; import java.io.IOException; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit;
import okhttp3.Connection; import okhttp3.Headers; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.internal.http.HttpHeaders; import okhttp3.internal.platform.Platform; import okio.Buffer; import okio.BufferedSource;
/**
@since 1.0.0 */ public final class LoggingInterceptor implements Interceptor { //一行字符最大数量 private static final int MAX_LENGTH = 1024;
private final Charset UTF8 = Charset.forName("UTF-8"); private final Logger logger; private volatile LoggingLevel level = LoggingLevel.NONE;
public LoggingInterceptor() { this(LoggingLevel.SINGLE); }
public LoggingInterceptor(LoggingLevel level) { this(level, Logger.DEFAULT); }
public LoggingInterceptor(LoggingLevel level, Logger logger) { this.level = level; if(this.level == null) { this.level = LoggingLevel.SINGLE; } this.logger = logger; }
/**
@return {@link LoggingInterceptor} */ public LoggingInterceptor setLevel(LoggingLevel level) { this.level = level; if(this.level == null) { this.level = LoggingLevel.BODY; }
return this; }
/**
@Override public Response intercept(Chain chain) throws IOException { return logIntercept(chain); }
/**
@throws IOException */ private Response logIntercept(Chain chain) throws IOException { Request request = chain.request();
long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch(IOException e) { print(String.format("┣━━━ [HTTP FAILED] url:%s exception:%s", request.url(), e.getMessage())); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
String httpHeaderString = getHttpHeaderString(request, response, tookMs, chain);
switch(level) { //do nothing // case NONE: // break; case URL_BODY: printUrlBody(request, response); break; case SINGLE: printSingle(request, response, httpHeaderString); break; case STATE: printState(httpHeaderString); break; case HEADERS: printHeaders(request, response, httpHeaderString); break; case BODY: printBody(request, response, httpHeaderString); break; case ALL: printAll(request, response, httpHeaderString); break; default: break; }
return response; }
/**
/**
@param text 要打印的文本 */ private void printLong(String text) { int length = text.length(); if(length <= MAX_LENGTH) { print(text); } else { int lineNum = length / MAX_LENGTH; if(length % MAX_LENGTH != 0) { lineNum++; }
for(int i = 1; i <= lineNum; i++)
{
if(i < lineNum)
{
print(text.substring((i - 1) * MAX_LENGTH, i * MAX_LENGTH));
}
else
{
print(text.substring((i - 1) * MAX_LENGTH, length));
}
}
} }
/**
private void printHeaders(Request request, Response response, String httpHeaderString) throws IOException { print(httpHeaderString); printHttpHeaders(request, response); printEnd(); }
/**
/**
/**
/**
/**
/**
/**
/**
/**
/**
@param response {@link Response} */ private void printHttpHeaders(Request request, Response response) throws IOException { RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; if(hasRequestBody) { print("Content-Length: " + requestBody.contentLength()); MediaType mediaType = requestBody.contentType(); // Request body headers are only present when installed as a network interceptor. Force // them to be included (when available) so there values are known. if(mediaType != null) { print("Content-Type: " + mediaType); }
Headers headers = request.headers();
for(int i = 0, count = headers.size(); i < count; i++)
{
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if(!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name))
{
print(name + ": " + headers.value(i));
}
}
}
Headers headers = response.headers(); if(headers != null) { for(int i = 0, count = headers.size(); i < count; i++) { print(headers.name(i) + ": " + headers.value(i)); } } }
/**
@return 响应体字符串 */ private String getResponseBody(Request request, Response response) throws IOException { String body = "[No Response Body]"; if(HttpHeaders.hasBody(response)) { ResponseBody responseBody = response.body(); BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer();
if(isEncoded(request.headers()))
{
body = "[Body: Encoded]";
}
else if(!isPlaintext(buffer))
{
String url = request.url().toString();
if(!url.contains("?"))
{
body = String.format("[File:%s]", url.substring(url.lastIndexOf("/") + 1));
}
else
{
body = "[Body: Not readable]";
}
}
else
{
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if(contentType != null)
{
charset = contentType.charset(UTF8);
}
body = buffer.clone().readString(charset);
}
}
return body; }
/**
log打印等级,默认提供了 {@link #DEFAULT},{@link #WARN} 两种等级,差别在Android Logcat中可以体现出来 */ public interface Logger { void log(String message);
/**
/**
/**
/**
import java.io.IOException;
import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part;
import com.alibaba.fastjson.JSONObject; import com.johnson4droid.server.utils.DateUtils; import com.johnson4droid.server.utils.IoUtils;
/**
Servlet implementation class ClientRequestHandler */ @WebServlet("/ClientRequestHandler") public class ClientRequestHandler extends HttpServlet { private static final long serialVersionUID = 1L;
/**
/**
/**
response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response);
/*
Part part1 = request.getPart("username"); String username = new String(IoUtils.inputStream2Bytes(part1.getInputStream())); System.out.println("username:" + username);
Part part2 = request.getPart("password"); String password = new String(IoUtils.inputStream2Bytes(part2.getInputStream())); System.out.println("password:" + password);
Part part3 = request.getPart("file"); byte[] fileBytes = IoUtils.inputStream2Bytes(part3.getInputStream()); String fileName = part3.getSubmittedFileName(); //中文文件名乱码 System.out.println("fileName:"+fileName); // IoUtils.saveBytes2File(fileBytes, fileName); String p3ContentType = part3.getContentType(); System.out.println("p3ContentType: "+p3ContentType); IoUtils.saveBytes2File(fileBytes, "C:/Users/johnson4droid/Desktop/files/" + DateUtils.format(System.currentTimeMillis()) + ".png"); /String _fileName = DateUtils.format(System.currentTimeMillis()) + ".png"; IoUtils.saveBytes2File(fileBytes, _fileName); System.out.println("_fileName : "+_fileName);/
JSONObject jsonResp = new JSONObject(); jsonResp.put("code", 0); jsonResp.put("msg", "success"); jsonResp.put("sessionId", request.getSession().getId());
// Send data to client. response.getWriter().write(jsonResp.toJSONString());
}
@Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { super.service(arg0, arg1); }
@Override protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { super.service(arg0, arg1); }
}`
在doPost方法中,我们接收字符串参数以及文件参数,并将接收到的文件保存到磁盘中。 以下是两个工具类的代码 `package com.johnson4droid.server.utils;
import java.text.SimpleDateFormat; import java.util.Calendar;
/**
*/ public final class DateUtils {
public static final String COMMON_FORMAT = "yyyyMMdd_HH_mm_ss"; private static final SimpleDateFormat DATE_FORMAT_COMMON = new SimpleDateFormat(COMMON_FORMAT);
/**
*/ public DateUtils() { }
public static String format(long time) { Calendar ca = Calendar.getInstance(); ca.setTimeInMillis(time); return DATE_FORMAT_COMMON.format(ca.getTime()); }
}`
`package com.johnson4droid.server.utils;
import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream;
/**
*/ public final class IoUtils {
/**
*/ public IoUtils() { }
public static byte[] inputStream2Bytes(InputStream is) { byte[] b = new byte[1024]; ByteArrayOutputStream baos = null; int len = 0;
try {
baos = new ByteArrayOutputStream();
while ((len = is.read(b)) != -1) {
baos.write(b, 0, len);
}
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* if (is != null) { try { is.close(); } catch (IOException e) {
* e.printStackTrace(); } }
*/
}
return null;
}
public static void saveBytes2File(byte[] fileBytes, String fileName) { FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
fos.write(fileBytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}`
最后贴一下web.xml中的配置 `
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>clientRequest</servlet-name>
<servlet-class>com.johnson4droid.server.ClientRequestHandler</servlet-class>
<multipart-config>
<max-file-size>1000000</max-file-size>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>clientRequest</servlet-name>
<url-pattern>/clientRequest</url-pattern>
</servlet-mapping>
`
最后将我们创建的服务端程序发布到Tomcat中即可完成服务端发布,可使用上面的客户端代码进行测试。
import java.io.File; import java.io.IOException;
import com.johnson4droid.client.log.LoggingInterceptor; import com.johnson4droid.client.log.LoggingLevel;
import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response;
/**
*/ public final class FileUploader {
/**
*/ public FileUploader() { }
public static void upload() { //OkHttpClient client = new OkHttpClient(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor(LoggingLevel.ALL)) //增加日志打印 .build();
}
public static void main(String[] args) { upload(); }
}`