cn.ipokerface.weixin.request.http.apache.FormBodyPart Maven / Gradle / Ivy
package cn.ipokerface.weixin.request.http.apache;
import cn.ipokerface.weixin.request.http.ContentType;
/**
* Created by PokerFace
* Create Date 2019-12-27.
* Email: [email protected]
* Version 1.0.0
*
* Description:
*/
public class FormBodyPart {
private final String name;
private final Header header;
private final ContentBody body;
FormBodyPart(final String name, final ContentBody body, final Header header) {
super();
this.name = name;
this.body = body;
this.header = header != null ? header : new Header();
}
/**
* (4.4) use
*/
public FormBodyPart(final String name, final ContentBody body) {
super();
this.name = name;
this.body = body;
this.header = new Header();
generateContentDisp(body);
generateContentType(body);
generateTransferEncoding(body);
}
public String getName() {
return this.name;
}
public ContentBody getBody() {
return this.body;
}
public Header getHeader() {
return this.header;
}
public void addField(final String name, final String value) {
this.header.addField(new MinimalField(name, value));
}
/**
* (4.4) use
*/
protected void generateContentDisp(final ContentBody body) {
final StringBuilder buffer = new StringBuilder();
buffer.append("form-data; name=\"");
buffer.append(getName());
buffer.append("\"");
if (body.getFilename() != null) {
buffer.append("; filename=\"");
buffer.append(body.getFilename());
buffer.append("\"");
}
addField(Mime.CONTENT_DISPOSITION, buffer.toString());
}
/**
* (4.4) use
*/
protected void generateContentType(final ContentBody body) {
final ContentType contentType;
if (body instanceof AbstractContentBody) {
contentType = ((AbstractContentBody) body).getContentType();
} else {
contentType = null;
}
if (contentType != null) {
addField(Mime.CONTENT_TYPE, contentType.toString());
} else {
final StringBuilder buffer = new StringBuilder();
buffer.append(body.getMimeType()); // MimeType cannot be null
if (body.getCharset() != null) { // charset may legitimately be null
buffer.append("; charset=");
buffer.append(body.getCharset());
}
addField(Mime.CONTENT_TYPE, buffer.toString());
}
}
/**
* (4.4) use
*/
protected void generateTransferEncoding(final ContentBody body) {
addField(Mime.CONTENT_TRANSFER_ENC, body.getTransferEncoding()); // TE cannot be null
}
}